//
//  MainViewController.swift
//  HMWeibo08
//
//  Created by 刘凡 on 15/7/27.
//  Copyright © 2015年 joyios. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        setupComposeButton()
    }
    
    /// 点击撰写按钮
    func clickComposeButton() {
        print(__FUNCTION__)
    }

    /// 设置撰写按钮位置
    private func setupComposeButton() {
        let w = tabBar.bounds.width / CGFloat(childViewControllers.count)
        let rect = CGRect(x: 0, y: 0, width: w, height: tabBar.bounds.height)
        
        composedButton.frame = CGRectOffset(rect, 2 * w, 0)
    }
    
    /// 添加所有子控制器
    private func addChildViewControllers() {
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }

    /// 添加控制器
    ///
    /// - parameter vc       : 视图控制器
    /// - parameter title    : 标题
    /// - parameter imageName: 图像名称
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
    
    // MARK: - 懒加载
    /// 撰写按钮
    private lazy var composedButton: UIButton = {
        let btn = UIButton()
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        // 懒加载中需要使用 self.
        self.tabBar.addSubview(btn)
        btn.addTarget(self, action: "clickComposeButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()
}
